export class GameManager {
  constructor() {
    this.rooms = new Map() // roomId -> GameRoom
    this.playerRooms = new Map() // playerId -> roomId
    this.playerSockets = new Map() // playerId -> socket
  }

  // 加入房间
  async joinRoom(roomId, playerId, playerName, socket) {
    try {
      let room = this.rooms.get(roomId)

      if (!room) {
        // 创建新房间
        room = new GameRoom(roomId)
        this.rooms.set(roomId, room)
        console.log(`创建新房间: ${roomId}`)
      }

      // 检查房间是否已满
      if (room.players.size >= 8) {
        return { success: false, error: "房间已满" }
      }

      // 检查玩家是否已在房间中
      if (room.players.has(playerId)) {
        return { success: false, error: "玩家已在房间中" }
      }

      // 创建玩家对象
      const player = {
        id: playerId,
        name: playerName,
        score: 0,
        isDrawing: false,
      }

      // 添加玩家到房间和维护 socket 映射
      room.addPlayer(player)
      this.playerRooms.set(playerId, roomId)
      this.playerSockets.set(playerId, socket)

      console.log(`玩家 ${playerName} 加入房间 ${roomId}，当前玩家数: ${room.players.size}`)

      return {
        success: true,
        player: player,
        gameState: room.getGameState(),
      }
    } catch (error) {
      console.error("加入房间错误:", error)
      return { success: false, error: "加入房间失败" }
    }
  }

  // 离开房间
  leaveRoom(roomId, playerId) {
    const room = this.rooms.get(roomId)
    if (!room) {
      return { success: false, error: "房间不存在" }
    }

    room.removePlayer(playerId)
    this.playerRooms.delete(playerId)
    this.playerSockets.delete(playerId)

    // 如果房间为空，删除房间
    if (room.players.size === 0) {
      room.cleanup()
      this.rooms.delete(roomId)
      console.log(`删除空房间: ${roomId}`)
    }

    return {
      success: true,
      players: Array.from(room.players.values()),
    }
  }

  // 获取玩家的 socket
  getPlayerSocket(playerId) {
    return this.playerSockets.get(playerId)
  }

  // 开始游戏
  async startGame(roomId, wordBankManager, gameConfig = {}) {
    const room = this.rooms.get(roomId)
    if (!room) {
      return { success: false, error: "房间不存在" }
    }

    if (room.players.size < 2) {
      return { success: false, error: "至少需要2个玩家才能开始游戏" }
    }

    if (room.gameStatus !== "waiting") {
      return { success: false, error: "游戏已经开始" }
    }

    // 设置游戏配置
    if (gameConfig.roundTime) {
      room.roundTime = Math.max(30, Math.min(300, gameConfig.roundTime));
    }
    if (gameConfig.wordBankId) {
      room.selectedWordBankId = gameConfig.wordBankId;
    }

    // 开始第一轮
    const result = await room.startNewRound(wordBankManager)

    return {
      success: true,
      gameState: room.getGameState(),
    }
  }

  // 开始下一轮
  async startNextRound(roomId, wordBankManager) {
    const room = this.rooms.get(roomId)
    if (!room) {
      return { success: false, error: "房间不存在" }
    }

    if (room.currentRound >= room.maxRounds) {
      // 游戏结束
      room.gameStatus = "finished"
      return {
        success: false,
        gameEnded: true,
        finalScores: room.getFinalScores(),
      }
    }

    const result = await room.startNewRound(wordBankManager)

    return {
      success: true,
      gameState: room.getGameState(),
    }
  }

  // 处理猜测
  async processGuess(roomId, playerId, guess) {
    const room = this.rooms.get(roomId)
    if (!room) {
      throw new Error("房间不存在")
    }

    const player = room.players.get(playerId)
    if (!player) {
      throw new Error("玩家不存在")
    }

    const isCorrect = room.checkGuess(guess)

    if (isCorrect) {
      // 猜对了，加分
      player.score += 10

      // 绘画者也加分
      const drawer = room.getCurrentDrawer()
      if (drawer) {
        drawer.score += 5
      }

      // 检查是否所有人都猜对了
      const roundEnded = room.checkRoundEnd()

      return {
        playerId,
        playerName: player.name,
        guess,
        isCorrect: true,
        roundEnded: true,
      }
    }

    return {
      playerId,
      playerName: player.name,
      guess,
      isCorrect: false,
      roundEnded: false,
    }
  }

  // 检查是否是当前绘画者
  isCurrentDrawer(roomId, playerId) {
    const room = this.rooms.get(roomId)
    return room && room.currentDrawer === playerId
  }

  // 添加笔画
  addStroke(roomId, stroke) {
    const room = this.rooms.get(roomId)
    if (room) {
      room.strokes.push(stroke)
    }
  }

  // 清除笔画
  clearStrokes(roomId) {
    const room = this.rooms.get(roomId)
    if (room) {
      room.strokes = []
    }
  }

  // 移除最后一笔
  removeLastStroke(roomId) {
    const room = this.rooms.get(roomId)
    if (room && room.strokes.length > 0) {
      room.strokes.pop()
    }
  }

  // 获取游戏状态
  getGameState(roomId) {
    const room = this.rooms.get(roomId)
    return room ? room.getGameState() : null
  }

  // 获取玩家所在房间
  getPlayerRoom(playerId) {
    return this.playerRooms.get(playerId)
  }

  // 更新剩余时间
  updateTimeLeft(roomId, timeLeft) {
    const room = this.rooms.get(roomId)
    if (room) {
      room.timeLeft = timeLeft
    }
  }

  // 获取分数
  getScores(roomId) {
    const room = this.rooms.get(roomId)
    if (!room) return {}

    const scores = {}
    room.players.forEach((player) => {
      scores[player.id] = player.score
    })
    return scores
  }

  // 设置房间计时器
  setRoomTimer(roomId, timer) {
    const room = this.rooms.get(roomId)
    if (room) {
      room.timer = timer
    }
  }

  // 获取活跃房间数
  getActiveRoomsCount() {
    return this.rooms.size
  }

  // 获取总玩家数
  getTotalPlayersCount() {
    let total = 0
    this.rooms.forEach((room) => {
      total += room.players.size
    })
    return total
  }

  restartGame(roomId) {
    const room = this.rooms.get(roomId)
    if (!room) {
      return { success: false, error: "房间不存在" }
    }

    // 重置游戏状态
    room.gameStatus = "waiting"
    room.currentRound = 0
    room.currentDrawer = null
    room.currentWord = null
    room.timeLeft = 0
    room.strokes = []
    room.drawerIndex = 0
    room.guessedPlayers.clear()

    // 重置玩家分数
    room.players.forEach((player) => {
      player.score = 0
      player.isDrawing = false
    })

    // 清理计时器
    if (room.timer) {
      clearInterval(room.timer)
      room.timer = null
    }

    return {
      success: true,
      gameState: room.getGameState(),
    }
  }
}

// 游戏房间类
class GameRoom {
  constructor(roomId) {
    this.roomId = roomId
    this.players = new Map() // playerId -> Player
    this.gameStatus = "waiting" // waiting, drawing, finished
    this.currentDrawer = null
    this.currentWord = null
    this.timeLeft = 60
    this.roundTime = 60 // 默认回合时长
    this.strokes = []
    this.currentRound = 0
    this.maxRounds = 5
    this.drawerIndex = 0
    this.timer = null
    this.guessedPlayers = new Set() // 已猜对的玩家
    this.selectedWordBankId = "" // 选定的词库ID
  }

  addPlayer(player) {
    this.players.set(player.id, player)
  }

  removePlayer(playerId) {
    this.players.delete(playerId)

    // 如果离开的是当前绘画者，需要切换
    if (this.currentDrawer === playerId && this.gameStatus === "drawing") {
      this.selectNextDrawer()
    }
  }

  async startNewRound(wordBankManager) {
    this.currentRound++
    this.gameStatus = "drawing"
    this.timeLeft = this.roundTime
    this.strokes = []
    this.guessedPlayers.clear()

    // 选择绘画者
    this.selectNextDrawer()

    // 选择词汇
    this.currentWord = wordBankManager.getRandomWord(this.selectedWordBankId)

    console.log(
      `房间 ${this.roomId} 第 ${this.currentRound} 轮开始，绘画者: ${this.currentDrawer}，词汇: ${this.currentWord}`,
    )

    return true
  }

  selectNextDrawer() {
    const playerIds = Array.from(this.players.keys())
    if (playerIds.length === 0) return

    // 重置所有玩家的绘画状态
    this.players.forEach((player) => {
      player.isDrawing = false
    })

    // 选择下一个绘画者
    this.currentDrawer = playerIds[this.drawerIndex % playerIds.length]
    this.drawerIndex++

    // 设置当前绘画者状态
    const drawer = this.players.get(this.currentDrawer)
    if (drawer) {
      drawer.isDrawing = true
    }
  }

  switchToNextDrawer() {
    this.selectNextDrawer()
  }

  getCurrentDrawer() {
    return this.players.get(this.currentDrawer)
  }

  checkGuess(guess) {
    if (!this.currentWord) return false

    // 简单的字符串匹配，忽略大小写和空格
    const normalizedGuess = guess.toLowerCase().trim()
    const normalizedWord = this.currentWord.toLowerCase().trim()

    return normalizedGuess === normalizedWord
  }

  checkRoundEnd() {
    // 检查是否所有非绘画者都猜对了
    return true;
    const nonDrawers = Array.from(this.players.keys()).filter((id) => id !== this.currentDrawer)
    return nonDrawers.every((id) => this.guessedPlayers.has(id))
  }

  getGameState() {
    return {
      roomId: this.roomId,
      players: Array.from(this.players.values()).map((p) => ({
        id: p.id,
        name: p.name,
        score: p.score,
        isDrawing: p.isDrawing,
      })),
      currentDrawer: this.currentDrawer,
      currentWord: this.currentWord,
      timeLeft: this.timeLeft,
      gameStatus: this.gameStatus,
      strokes: this.strokes,
      currentRound: this.currentRound,
      maxRounds: this.maxRounds,
    }
  }

  getFinalScores() {
    const scores = []
    this.players.forEach((player) => {
      scores.push({
        id: player.id,
        name: player.name,
        score: player.score,
      })
    })

    // 按分数排序
    return scores.sort((a, b) => b.score - a.score)
  }

  cleanup() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  }
}
